<template>
  <view v-if="!loading" class="due-index">
    <!-- #ifdef MP-WEIXIN -->
    <uv-navbar
      :fixed="false"
      :title="title"
      left-arrow
      @leftClick="$onClickLeft"
    />
    <!-- #endif -->
    <view class="nav">
      <view class="header">
        <view class="mr-1"
          ><image :src="store.image" style="width: 80rpx; height: 80rpx"></image
        ></view>
        <view class="left">
          <view class="store-name">
            <text>{{ store.name }}</text>
            <!-- <view class="iconfont iconarrow-right"></view> -->
          </view>
          <view class="store-location">
            <text
              >{{ currentLanguageTexts.distanceFromYou }} {{ store.dis }}</text
            >
          </view>
        </view>
        <view class="right" v-if="store.status == 1">
          <view class="dinein active">
            <text>{{ currentLanguageTexts.shopOpen }} </text>
          </view>
        </view>
        <view class="right" v-else>
          <view class="takeout">
            <text>{{ currentLanguageTexts.ClosedBusiness }} </text>
          </view>
        </view>
      </view>
    </view>
    <view class="due-index__form">
      <uv-form
        labelPosition="left"
        :labelWidth="160"
        :labelStyle="{ color: '#596375' }"
      >
        <uv-form-item :label="currentLanguageTexts.secondMemberCount">
          <uv-number-box
            v-model="bookInfo.memberCount"
            :min="1"
            :max="30"
          ></uv-number-box>
        </uv-form-item>
        <uv-form-item
          :label="currentLanguageTexts.secondMealTime"
          :customStyle="{ marginTop: '20rpx' }"
        >
          <uv-input
            disabled
            disabledColor="#ffffff"
            :placeholder="
              currentLanguageTexts.secondMealTime +
              '(' +
              currentLanguageTexts.secondMealTimeFormt +
              ')'
            "
            suffixIcon="arrow-down"
            v-model="mealDate"
            @click="datePickerRef.open()"
          >
          </uv-input>
        </uv-form-item>
        <uv-form-item
          :label="currentLanguageTexts.secondContact"
          :customStyle="{ marginTop: '20rpx' }"
        >
          <uv-input
            :placeholder="currentLanguageTexts.secondContact"
            v-model="bookInfo.user_name"
          >
          </uv-input>
        </uv-form-item>

        <uv-form-item
          :label="currentLanguageTexts.recipientPhone"
          :customStyle="{ marginTop: '20rpx' }"
        >
          <view class="contract">
            <view class="contract__pre" @click="phoneRegionCodeRef.open()">
              {{ bookInfo.code }}
              <uv-icon name="arrow-down" color="#999"></uv-icon>
            </view>
            <uv-input
              v-model="bookInfo.phone"
              :placeholder="currentLanguageTexts.recipientPhone"
              type="number"
              :maxlength="11"
            >
            </uv-input>
          </view>
        </uv-form-item>
      </uv-form>
      <view class="btn">
        <uv-button
          :custom-style="{
            borderRadius: '40rpx',
            background: '#fae358',
            fontWeight: 'bold',
            borderColor: '#fae358',
          }"
          @click="handleSubmit"
          :loading="btnLoading"
          >{{ currentLanguageTexts.ConfirmAppointment }}
        </uv-button>
      </view>
    </view>

    <uv-picker
      ref="datePickerRef"
      round="8"
      :columns="datePickerColumns"
      :defaultIndex="defaultIndex"
      @confirm="confirmDatePicker"
      :confirmText="currentLanguageTexts.confirm"
      :cancelText="currentLanguageTexts.cancel"
    ></uv-picker>
  </view>
  <phoneRegionCode
    ref="phoneRegionCodeRef"
    @confirm="(v) => (bookInfo.code = v)"
  />

  <!-- <view class="loading" v-else>
    <uv-loading-icon color="#DA5650" size="40" mode="circle"></uv-loading-icon>
    <button
      type="primary"
      style="z-index: 3001; position: absolute; top: 650rpx; left: 260rpx"
      @click="init"
      v-if="!store.id"
    >
      定位最近的门店
    </button>
  </view> -->
</template>

<script setup>
import { ref, computed } from 'vue';
import { useMainStore } from '@/store/store';
import { storeToRefs } from 'pinia';
import { onLoad, onShow, onPullDownRefresh, onHide } from '@dcloudio/uni-app';
import { formatDateTime, kmUnit } from '@/utils/util';

import dayjs from '@/uni_modules/uv-ui-tools/libs/util/dayjs';
import { getList, getDetail, DoBookTable, DoGetShopList } from '@/api/due';
import { shopNearby } from '@/api/goods';
import phoneRegionCode from '@/pages/components/phoneRegionCodePicker/index.vue';

const main = useMainStore();
const {
  orderType,
  store,
  isLogin,
  location,
  tgUser,
  currentLanguageTexts,
  member,
} = storeToRefs(main);
const title = ref(currentLanguageTexts.value.due);
const list = ref([]);
const phoneRegionCodeRef = ref();

const loading = ref(true);
const datePickerRef = ref();
const mealHours = [
  { label: '00' },
  { label: '01' },
  { label: '02' },
  { label: '03' },
  { label: '04' },
  { label: '05' },
  { label: '06' },
  { label: '07' },
  { label: '08' },
  { label: '09' },
  { label: '10' },
  { label: '11' },
  { label: '12' },
  { label: '13' },
  { label: '14' },
  { label: '15' },
  { label: '16' },
  { label: '17' },
  { label: '18' },
  { label: '19' },
  { label: '20' },
  { label: '21' },
  { label: '22' },
  { label: '23' },
];
const mealMin = [
  { label: '00' },
  { label: '10' },
  { label: '20' },
  { label: '30' },
  { label: '40' },
  { label: '50' },
];

const dateArr = ref([]);
const btnLoading = ref(false);

const datePickerColumns = computed(() => {
  return [
    dateArr.value,
    mealHours.map((el) => el.label),
    mealMin.map((el) => el.label),
  ];
});
const defaultIndex = ref([]);

const bookInfo = ref({
  date: [],
  memberCount: 1,
  user_name: tgUser.value.user_name,
  phone: member.value.mobile,
  code: '+855',
  mealTime: '',
});
const mealDate = computed(() => {
  const date = bookInfo.value.date;
  if (date.length === 0) return '';
  return date[0] + ' ' + date[1] + ':' + date[2];
});

const { max_reserve_days, end_time, start_time, id } = store.value;
const startHour = dayjs(start_time).format('HH');
const endHour = dayjs(end_time).format('HH');
const endTime = dayjs(end_time).format('HH:mm');

function getCurrentTimeInTimeZone(timeZone) {
  const now = new Date();
  const formatter = new Intl.DateTimeFormat('en-US', {
    timeZone: timeZone,
    hour12: false, // 使用24小时制
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
  return formatter.format(now);
}

const init = () => {
  //页面初始化
  loading.value = true;
  const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

  const userTime = getCurrentTimeInTimeZone(userTimeZone);

  let currentDateEndTime = dayjs(userTime).format('YYYY-MM-DD') + ' ' + endTime;
  if (Number(startHour) > Number(endHour)) {
    currentDateEndTime = dayjs(currentDateEndTime)
      .add(1, 'day')
      .format('YYYY-MM-DD HH:mm');
  }
  // 计算时间差，如果预定时间不在营业时间范围内，就是明天后天大后天
  const dateDiff = dayjs(userTime).diff(currentDateEndTime);

  let i = 0;
  if (dateDiff > 0 && Number(startHour) < Number(endHour)) {
    i = 1;
  }

  const maxServerDays = max_reserve_days + i;

  for (i; i < maxServerDays; i++) {
    dateArr.value.push(dayjs(userTime).add(i, 'day').format('MM-DD'));
  }
  // 大于0 就是今天已经过了，那么就从明天开始
  if (dateDiff > 0) {
    bookInfo.value.date = [
      datePickerColumns.value[0][0],
      datePickerColumns.value[1][0],
      datePickerColumns.value[2][0],
    ];
  } else {
    const curDate = dayjs(userTime).format('MM-DD');
    const curHour = dayjs(userTime).format('HH');
    const curSecond = dayjs(userTime).format('mm');

    let fIndex =
      datePickerColumns.value[0].findIndex((el) => curDate === el) || 0;
    let sIndex = datePickerColumns.value[1].findIndex(
      (el) => Number(curHour) <= Number(el)
    );
    let tIndex = datePickerColumns.value[2].findIndex(
      (el) => Number(curSecond) <= Number(el)
    );
    if (tIndex == -1 && sIndex !== -1) {
      tIndex = 0;
      fIndex = 0;
      sIndex += 1;
    }
    if (sIndex == -1) {
      fIndex += 1;
      sIndex = 0;
      tIndex = 0;
    }
    defaultIndex.value = [fIndex, sIndex, tIndex];
    bookInfo.value.date = [
      datePickerColumns.value[0][fIndex],
      datePickerColumns.value[1][sIndex],
      datePickerColumns.value[2][tIndex],
    ];
  }
  loading.value = false;
};

uni.$on('refreshMenu', () => {
  // 在这里执行onLoad逻辑
  init();
});

const confirmDatePicker = ({ value }) => {
  bookInfo.value.date = value;
};

// 提交预约
const handleSubmit = () => {
  if (!isLogin.value) {
    return uni.navigateTo({ url: '/pages/components/pages/login/login' });
  }
  const { user_name, phone, date, code } = bookInfo.value;
  if (!user_name) {
    return uni.showToast({
      icon: 'none',
      title: currentLanguageTexts.value.secondContactPlaceholder,
    });
  }
  if (!bookInfo.value.phone) {
    return uni.showToast({
      icon: 'none',
      title: currentLanguageTexts.value.secondContactTelPlaceholder,
    });
  }
  const startTime = dayjs(start_time).format('HH:mm');
  const currentYear = dayjs().year();
  bookInfo.value.mealTime =
    currentYear + '-' + date[0] + ' ' + date[1] + ':' + date[2];
  // 不能选择过去了的时间
  if (dayjs().diff(bookInfo.value.mealTime) > 0) {
    return uni.showToast({
      icon: 'none',
      title: currentLanguageTexts.value.PleaseCorrectTime,
    });
  }
  if (
    dayjs(currentYear + '-' + date[0] + ' ' + startTime).diff(
      bookInfo.value.mealTime
    ) > 0 &&
    dayjs(currentYear + '-' + date[0] + ' ' + endTime).diff(
      bookInfo.value.mealTime
    ) < 0
  ) {
    return uni.showToast({
      icon: 'none',
      title: currentLanguageTexts.value.ThisTime,
    });
  }
  btnLoading.value = true;
  DoBookTable({
	id: member.value.id,
    ...tgUser.value,
    ...bookInfo.value,
    // mealTime 转为时间戳
    mealTime: dayjs(bookInfo.value.mealTime).unix(),
    shop_id: id,
    phone: code + '-' + phone,
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
  })
    .then(() => {
      uni.showToast({
        title: currentLanguageTexts.value.BookingSuccessful,
      });
      uni.navigateBack({ delta: 2 });
    })
    .finally(() => {
      btnLoading.value = false;
    });
};

onLoad(() => {
   init();
});
</script>

<style lang="scss" scoped>
.due-index {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  &__form {
    flex: 1 0 0;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border-top: 2rpx solid #f7f7f7;
    padding: 20rpx;
    .contract {
      display: flex;
      width: 100%;
      justify-content: space-between;
      &__pre {
        display: flex;
        width: 160rpx;
        justify-content: center;
        align-items: center;
        gap: 10rpx;
        border: 1rpx solid #dadbde;
        border-radius: 8rpx;
      }
    }
  }
  .btn {
    margin-bottom: 40rpx;
  }
}
.nav {
  width: 100%;
  //height: 212rpx;
  height: 140rpx;
  display: flex;
  flex-direction: column;

  .header {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    background-color: #ffffff;
    height: 140rpx;

    .left {
      flex: 1;
      display: flex;
      flex-direction: column;

      .store-name {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        font-size: $font-size-lg;
        margin-bottom: 10rpx;
        .small {
          font-size: $font-size-sm;
          color: $text-color-assist;
        }
        .iconfont {
          margin-left: 10rpx;
          line-height: 100%;
        }
      }

      .store-location {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: $text-color-assist;
        font-size: $font-size-sm;

        .iconfont {
          vertical-align: middle;
          display: table-cell;
          color: $color-primary;
          line-height: 100%;
        }
      }
    }

    .right {
      //background-color: $bg-color-grey;
      border-radius: 38rpx;
      display: flex;
      align-items: center;
      font-size: $font-size-sm;
      padding: 0 38rpx;
      color: $text-color-assist;

      .dinein,
      .takeout {
        position: relative;
        display: flex;
        align-items: center;
        &.active {
          padding: 14rpx 38rpx;
          color: rgb(90, 91, 92);
          background-color: $color-primary;
          //background-color: #5A5B5C;
          border-radius: 38rpx;
        }
      }

      .takeout {
        margin-left: 20rpx;
        height: 100%;
        flex: 1;
        padding: 14rpx 0;
      }

      .dinein.active {
        margin-left: -38rpx;
      }

      .takeout.active {
        margin-right: -38rpx;
      }
    }
  }
}
</style>
